<template>
	<!--表格文件-->
	<view class="page-content">
		<view class="page-top">
			<!-- 标题栏和状态栏占位符 -->
			<view class="titleNview-placing"></view>
			<!-- 标题+筛选 -->
			<w-tit 
			leftIcon="arrowleft" 
			color="#595757" 
			background="#fff" 
			fontweight="600"
			:title="page_title"
			rightIcon="plusempty"
			:userType="userType"
			@clickRight="clickRight">
			</w-tit>
		</view>
		<scroll-view class="page-body" :scroll-top="scrollTop" scroll-y="true" @scrolltolower="loadmore()">
			<!--动态-->
			<template v-if="objlist && objlist.length > 0 ">
				<view class="body-box">
					<block v-for="(item,index) in objlist" :key="index">
						<view class="box-li" @click.stop="todown(item.url)">
							<view class="box-li-l">
								<image class="box-li-l-img" :src="$mAssetsPath.icon_word"></image>
								<view class="box-li-l-txt">
									<view class="title">{{item.name}}</view>
									<view class="time">{{item.create_time}}</view>
								</view>
							</view>
							<view class="box-li-r" v-if="userType !== 'index'"  @click.stop="deletes(item.id)">
								<image class="box-li-r-icon" :src="$mAssetsPath.icon_shanchu"></image>
							</view>
						</view>
					</block>
				</view>
				<!-- 上拉加载 -->
				<view class="det-con-more">
					<load-more :loadmore="load_more1"></load-more>
				</view>
			</template>
			<!--无数据-->
			<empty v-else no-full type="noData"></empty>
		</scroll-view>
		<!--编辑框-->
		<w-popup :show="showtip" :type="type1" @change="change1">
			<view class="w-tip">
				<view class="w-tit">提示</view>
				<view class="w-con">
					<view class="txt-row">是否该删除？</view>
				</view>
				<view class="w-but">
					<view class="w-but-txt" @click="cancel('tip')">取消</view>
					<view class="w-but-txt" @click="confirm">确认</view>
				</view>
			</view>
		</w-popup>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapActions
	} from "vuex";
	import {
		getPictureLists, //文件列表
		uploadPictureAlbumImgs, //文件上传
		getOssUploadsParams, //
		delPictureDatas, //删除文件
	} from '@/common/api.js';
	import wTit from '@/components/w-tit/w-tit-back.vue'; //标题
	import loadMore from '@/components/uni-load-more/load-more.vue';
	import picLi from '@/pages/components/pic_book_li.vue';
	import wPopup from '@/components/w-popup/w-popup2.vue'; // 弹窗
	export default {
		components: {
			loadMore,
			picLi,
			wTit,
			wPopup
		},
		data() {
			return {
				showtip: false, //是否显示弹窗2
				content1: '顶部弹 popup',
				type1: '', //弹窗显示方式
				
				scrollTop: 0,
				noData: false,
				load_more1: '', //下拉加载文字
				load_sta: false, //是否是加载状态
				page_title: '',
				objlist: [],
				params:{
					company_id:'',
					product_album_id:'',
					attr_arr:[],
					type:'1',
					page:1,
					limit:20
				},
				sel_id:0,
				userType:''
			}
		},
		computed: {
			...mapGetters(['companyInfo','userInfo']),
			img_width() {
				return (this.system.w - 42) / 3;
			}
		},
		onShow() {
			this.params.company_id = this.companyInfo.id;
			this.getdata();
		},
		onLoad(option) {
			console.log(222, option)
			if (!!option.title) {
				this.page_title = option.title;
			}
			if(option.id){
				this.params.product_album_id = option.id;
			}
			if(option.userType){
				this.userType = option.userType;
			}
		},
		methods: {
			todown(url) {
				console.log(123,url)
				uni.downloadFile({
					url: url, //仅为示例，并非真实的资源
					success: (data) => {
						uni.saveFile({
							tempFilePath: data.tempFilePath,
							success: function(res) {
								var savedFilePath = res.savedFilePath;
								uni.showToast({
									icon: 'none',
									mask: true,
									title: '文件已保存：' + res.savedFilePath, //保存路径
									duration: 3000,
								});
								setTimeout(() => {
									//打开文档查看
									uni.openDocument({
										filePath: res.savedFilePath,
										success: function(val) {}
									});
								}, 3000)
							},
							fail: (err) => {
								uni.showToast({
									icon: 'none',
									mask: true,
									title: '失败请重新下载',
								});
							},
						});
					}
				});
			},
			getdata(){
				getPictureLists(this.params).then(res=>{
					if(res.code === 2000){
						this.objlist = res.data.data;
					}
				})
			},
			//删除
			deletes(id){
				this.sel_id = id;
				this.showtip = true;
				this.content1 = 'center';
				this.type1 = 'center';
			},
			clickRight(){
				let that = this;
				// #ifdef APP-PLUS
				if (plus.os.name.toLowerCase() != "android") {
					uni.showModal({
						title: '提示',
						content: '仅支持Android平台',
						success: function(res) {}
					});
					return false
				}
				
				let main = plus.android.runtimeMainActivity();
				let Intent = plus.android.importClass("android.content.Intent");
				let fileIntent = new Intent(Intent.ACTION_GET_CONTENT)
				//fileIntent.setType(“image/*”);//选择图片
				//fileIntent.setType(“audio/*”); //选择音频
				//fileIntent.setType(“video/*”); //选择视频 （mp4 3gp 是android支持的视频格式）
				//fileIntent.setType(“video/*;image/*”);//同时选择视频和图片
				fileIntent.setType("*/*"); //无类型限制
				fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
				main.startActivityForResult(fileIntent, 1);
				// 获取回调
				main.onActivityResult = function(requestCode, resultCode, data) {
					let Activity = plus.android.importClass("android.app.Activity");
					let ContentUris = plus.android.importClass("android.content.ContentUris");
					let Cursor = plus.android.importClass("android.database.Cursor");
					let Uri = plus.android.importClass("android.net.Uri");
					let Build = plus.android.importClass("android.os.Build");
					let Environment = plus.android.importClass("android.os.Environment");
					let DocumentsContract = plus.android.importClass("android.provider.DocumentsContract");
					let MediaStore = plus.android.importClass("android.provider.MediaStore");
					// 给系统导入 contentResolver
					let contentResolver = main.getContentResolver()
					plus.android.importClass(contentResolver);
					// 返回路径
					let path = '';
					if (resultCode == Activity.RESULT_OK) {
					let uri = data.getData()
					if ("file" == uri.getScheme().toLowerCase()) { //使用第三方应用打开
						path = uri.getPath();
						return;
					}
					if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { //4.4以后
						path = getPath(this, uri);
					} else { //4.4以下下系统调用方法
						path = getRealPathFromURI(uri)
					}
					// 回调
						that.resultPath(path)
					}
					// 4.4 以上 从Uri 获取文件绝对路径
					function getPath(context, uri) {
						let isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
						let scheme = uri.getScheme().toLowerCase()
						if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
							// ExternalStorageProvider
							if (isExternalStorageDocument(uri)) {
								let docId = DocumentsContract.getDocumentId(uri);
								let split = docId.split(":");
								let type = split[0];
								// 如果是手机内部存储
								if ("primary" == type.toLowerCase()) {
									return Environment.getExternalStorageDirectory() + "/" + split[1];
								} else {
									return '/storage/' + type + "/" + split[1];
								}
							}
							// DownloadsProvider
							else if (isDownloadsDocument(uri)) {
								let id = DocumentsContract.getDocumentId(uri);
								let split = id.split(":");
								return split[1]
								// let contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), id);
								// return getDataColumn(context, contentUri, null, null);
							}
								// MediaProvider
							else if (isMediaDocument(uri)) {
								let docId = DocumentsContract.getDocumentId(uri);
								let split = docId.split(":");
								let type = split[0];
								let contentUri = null;
								if ("image" == type.toLowerCase()) {
									contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
								} else if ("video" == type.toLowerCase()) {
									contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
								} else if ("audio" == type.toLowerCase()) {
									contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
								}
								let selection = "_id=?";
								let selectionArgs = [split[1]];
								return getDataColumn(context, contentUri, selection, selectionArgs);
							}
						}
						// MediaStore (and general)
						else if ("content" == scheme) {
							return getDataColumn(context, uri, null, null);
						}
						// File
						else if ("file" == scheme) {
							return uri.getPath();
						}
					}
				
					// 4.4 以下 获取 绝对路径
					function getRealPathFromURI(uri) {
						let res = null
						let proj = [MediaStore.Images.Media.DATA]
						let cursor = contentResolver.query(uri, proj, null, null, null);
						if (null != cursor && cursor.moveToFirst()) {;
							let column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
							res = cursor.getString(column_index);
							cursor.close();
						}
						return res;
					}
				
					// 通过uri 查找出绝对路径
					function getDataColumn(context, uri, selection, selectionArgs) {
						let cursor = null;
						let column = "_data";
						let projection = [column];
						// let contentResolver = context.getContentResolver()
						// plus.android.importClass(contentResolver);
						cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
						if (cursor != null && cursor.moveToFirst()) {
							let column_index = cursor.getColumnIndexOrThrow(column);
							return cursor.getString(column_index);
						}
					}
								
					function isExternalStorageDocument(uri) {
						return "com.android.externalstorage.documents" == uri.getAuthority() ? true : false
					}
								
					function isDownloadsDocument(uri) {
						return "com.android.providers.downloads.documents" == uri.getAuthority() ? true : false
					}
								
					function isMediaDocument(uri) {
						return "com.android.providers.media.documents" == uri.getAuthority() ? true : false
					}
				}
				// #endif
			},
			resultPath(e){
				// e 为解析出来的文件本地路径
				let _self = this;
				let fIndex =e.lastIndexOf(".");
				let fileType =e.substr(fIndex+1);   //文件后缀
				let file_name = new Date().getTime() + Math.random().toString(36).substring(3, 20) + '.' + fileType;
				
				var temp_data = e.split("/")
				let filename = temp_data[temp_data.length-1];
				console.log(999,filename)
				
				//判断是否为图片
				function isAssetTypeAnImage(ext) {
				  return ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(ext.toLowerCase()) !== -1;
				}
				
				//判断是否为文档		
				function isAssetFile(ext) {
					return ['txt','pdf','doc','xls','xlsx','ppt','docx'].indexOf(ext.toLowerCase()) !== -1;
				}
							
				//图片上传调用
				if(isAssetTypeAnImage(fileType)){
					uni.uploadFile({
						url: this.$Base_Url + '/api/work_img', //仅为示例，非真实的接口地址
						filePath:"file:/"+ e,
						name: 'img',
						formData: {},
						header:{  //仅为示例，非真实的请求header
							// 'nktjj_session': uni.getStorageSync("c") || '',
							//"cookie": 'nktjj_session=' + uni.getStorageSync("c") || '',
							// 'X-Requested-With': 'XMLHttpRequest',
							// 'Content-Type': 'application/json; charset=UTF-8'
						},
						success: (uploadFileRes) => {
							
							//这里会有一个坑
							//如果是上传完就要预览图片，若后端没有返回线上路径，需要你通过通过访问本地图片路径
						//请在取得的本地路径前 加上一个“file://”
							
							let abc ="file://"+e;  //本地路径
							let imgUrl= JSON.parse(uploadFileRes.data).data.imgUrl;	//后端返回的值     
						}
					});
				}
							
				//文档上传调用		
				if(isAssetFile(fileType)){	
					getOssUploadsParams().then(res => {
						console.log(8888,res)
						uni.uploadFile({
							url: res.data.host,
							filePath:"file:/"+ e,
							name: 'file',
							formData: {
								name: "file:/"+ e,
								'key': res.data.dir + file_name,
								'policy': res.data.policy,
								'OSSAccessKeyId': res.data.accessid,
								'success_action_status': '200',
								//让服务端返回200,不然，默认会返回204
								'signature': res.data.signature,
							},
							success: (res2) => {
								console.log('upload-res', res2)
								// _self.objdata.person.img = res.data.host + '/' + res.data.dir + file_name;
								const url = res.data.host + '/' + res.data.dir + file_name;
								console.log(9988,url)
								uploadPictureAlbumImgs({
									company_id:_self.params.company_id,
									url:url,
									type:1,
									name:filename,
									product_album_id:_self.params.product_album_id,
								}).then(res3=>{
									if(res3.code === 2000){
										console.log(9999,res3)
										_self.getdata();
									}
								})			
							},
							fail: (err) => {
								console.log('uploadImage fail', err);
							}
						});
					})
					/* uni.uploadFile({
						url: this.$Base_Url + '/api/work_file', //仅为示例，非真实的接口地址
						filePath:"file:/"+ e,
						name: 'file',
						formData: {},
						header:{ 仅为示例，非真实的请求header
							// 'nktjj_session': uni.getStorageSync("c") || '',
							//"cookie": 'nktjj_session=' + uni.getStorageSync("c") || '',
							// 'X-Requested-With': 'XMLHttpRequest',
							// 'Content-Type': 'application/json; charset=UTF-8'
						},
						success: (uploadFileRes) => {
							let fileId= JSON.parse(uploadFileRes.data).data.file_id; 
						}
					}); */
				}
			},


			// //跳转新增页面
			// clickRight(){
			// 	let _self = this;
			// 	// #ifdef APP-PLUS
			// 	var REQUESTCODE = 1;
			// 	var main = plus.android.runtimeMainActivity();
			// 	var Intent = plus.android.importClass('android.content.Intent');
			// 	var intent = new Intent(Intent.ACTION_GET_CONTENT);
			// 	intent.setType('*/*'); //设置类型，任意类型
			// 	//intent.setType("image/*");
			// 	//intent.setType("audio/*"); //选择音频
			// 	//intent.setType("video/*"); //选择视频 （mp4 3gp 是android支持的视频格式）
				
			// 	intent.addCategory(Intent.CATEGORY_OPENABLE);
			// 	main.startActivityForResult(intent, REQUESTCODE);
			// 	main.onActivityResult = async function(requestCode, resultCode, data) {
			// 		console.log(3333,requestCode, resultCode, data)
			// 		if (REQUESTCODE == requestCode) {
			// 			var context = main;
			// 			plus.android.importClass(data);
			// 			// 获得文件路径
			// 			var fileData = data.getData();
			// 			var path = plus.android.invoke(fileData, 'getPath');
			// 			var temp_data = path.split("/")
			// 			var name = temp_data[temp_data.length-1].split(".")[0];
			// 			console.log('path:' + temp_data[temp_data.length-1]);
				
			// 			// 判断文件类型
			// 			var resolver = context.getContentResolver();
			// 			var fileType = plus.android.invoke(resolver, 'getType', fileData);
			// 			console.log('fileType:',fileType ,fileType.split("/")[0],'.' + temp_data[temp_data.length-1].split(".")[1]);
			// 			const url = await _self.uploadFile(path, fileType.split("/")[0], '.' + temp_data[temp_data.length-1].split(".")[1])
			// 			console.log(888,url)
						
			// 			uploadPictureAlbumImgs({
			// 				company_id:_self.params.company_id,
			// 				url:url,
			// 				type:1,
			// 				name:name,
			// 				product_album_id:_self.params.product_album_id,
			// 			}).then(res=>{
			// 				if(res.code === 2000){
			// 					console.log(9999,res)
			// 					_self.getdata();
			// 				}
			// 			})
			// 		}
			// 	};
			// 	// #endif
			// 	// #ifdef H5
			// 	var x = document.createElement('input');
			// 	x.setAttribute('type', 'file');
			// 	x.click();
			// 	x.onchange = function() {
			// 		console.log(this.files[0]);
			// 	};
			// 	// #endif
			// },

			// 上传文件
			uploadFile(file_path, fileType, type) {
				console.log('uploadFile', file_path, fileType, type);
				return new Promise((resolve, reject) => {
					//let suffix = "."+filename.extname;
					let file_name = new Date().getTime() + Math.random().toString(36).substring(3, 20) + type;
					getOssUploadsParams().then(res => {
						console.log(8888,res)
						let uploadTask = uni.uploadFile({
							url: res.data.host,
							filePath: "file:/"+ file_path,
							name: 'file',
							formData: {
								name: file_path,
								'key': res.data.dir + file_name,
								'policy': res.data.policy,
								'OSSAccessKeyId': res.data.accessid,
								'success_action_status': '200',
								//让服务端返回200,不然，默认会返回204
								'signature': res.data.signature,
							},
							success: (res2) => {
								console.log('upload-res', res2)
								// _self.objdata.person.img = res.data.host + '/' + res.data.dir + file_name;
								const url = res.data.host + '/' + res.data.dir + file_name;
								resolve(url)
							},
							fail: (err) => {
								console.log('uploadImage fail', err);
								uni.showModal({
									content: err.errMsg,
									showCancel: false
								});
								reject()
							}
						});
					})
				})
			},
			
			//跳转详细页
			toDet(id) {

			},
			loadmore() {

			},
			confirm(){
				delPictureDatas({
					id:this.sel_id,
					company_id:this.params.company_id
				}).then(res=>{
					if(res.code === 2000){
						uni.showToast({
							title:'删除成功！',
							icon:'none',
							duration:2000
						})
						this.getdata();
					}
				})
				this.showtip = false;
			},
			//取消
			cancel() {
				this.show = false
				this.showtip = false
			},
			change1(e) {
				if (!e.show) {
					this.showtip = false
				}
			},
		}
	}
</script>

<style lang="scss">
	/* 提示窗口 */
	.w-tip {
		/* #ifndef APP-NVUE */
		display: flex;
		flex-direction: column;
		/* #endif */
		width: 70vw;
		border-radius: 10rpx;
		background-color: #fff;
		box-shadow: 0rpx 7rpx 7rpx 0rpx rgba(0, 0, 0, 0.1);
		margin: 30rpx auto 0;
	
		.w-tit {
			font-size: 36rpx;
			font-weight: bold;
			color: $font-color-3;
			line-height: 60rpx;
			height: 60rpx;
			margin-top: 20rpx;
			text-align: center;
		}
	
		.w-but {
			display: flex;
			font-size: 32rpx;
			font-weight: 400;
			color: $font-color-b3;
			height: 84rpx;
			line-height: 84rpx;
	
			.w-but-txt {
				flex: 1;
				text-align: center;
				border-right: 1rpx solid #f5f5f5;
			}
	
			.w-but-txt:last-of-type {
				border-right: none;
			}
		}
	
		.w-con {
			display: flex;
			text-align: center;
			font-weight: 400;
			padding: 30rpx 30rpx;
			border-bottom: 1rpx solid #f5f5f5;
	
			.txt-row {
				width: 100%;
				text-align: center;
				font-size: 28rpx;
				color: $font-color-9;
			}
		}
	}
	.titleNview-placing {
		height: var(--status-bar-height);
		box-sizing: content-box;
		background: $uni-bg-color;
		display: block;
		position: sticky;
		top: 0rpx;
		z-index: 9999;
		overflow: hidden
	}

	.page-content {
		width: 100vw;
		height: 100%;

		.page-top {
			display: flex;
			flex-direction: column;
			box-sizing: content-box;
			background: $uni-bg-color;
			display: block;
			position: sticky;
			top: 0rpx;
			z-index: 9999;
			border-bottom: 1rpx solid #F2F4F5;
		}

		.page-body {
			display: flex;
			height: calc(100% - 90rpx - var(--status-bar-height));
			padding:0;

			.body-box {
				display: flex;
				flex-direction: column;
				background: $uni-bg-color;
				padding: 30rpx 30rpx 0 30rpx;
				margin-bottom: 20rpx;
				.box-li{
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 30rpx;
					.box-li-l{
						display: flex;
						align-items: center;
						.box-li-l-img{
							width: 40rpx;
							height: 48rpx;
							margin-right: 34rpx;
						}
						.box-li-l-txt{
							display: flex;
							flex-direction: column;
							.title{
								font-size: 32rpx;
								font-weight: 400;
								color: $font-color-3;
								line-height: 50rpx;
							}
							.time{
								font-size: 24rpx;
								font-weight: 400;
								color: $font-color-9;
								line-height: 40rpx;
							}
						}
					}
					.box-li-r{
						display: flex;
						.box-li-r-icon{
							width: 32rpx;
							height: 34rpx;
						}
					}
				}
			}
		}
	}
</style>
